package com.mai4j.maiadmin.validation.constraintvalidators;


import com.mai4j.maiadmin.validation.constraints.Equal;
import org.jooq.tools.reflect.Reflect;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * Created by 席有芳 on 2021/12/5.
 *
 * @author 席有芳
 */
public class EqualValidator implements ConstraintValidator<Equal, Object> {
    /**
     * 比较字段
     */
    private String from;
    /**
     * 被比较字段
     */
    private String to;
    /**
     * 信息
     */
    private String message;

    @Override
    public void initialize(Equal equal) {
        this.from = equal.from();
        this.to = equal.to();
        this.message = equal.message();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) return true;
        Object f = Reflect.on(value).field(from).get();
        Object t = Reflect.on(value).field(to).get();
        boolean isValid = Objects.equals(f, t);
        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addPropertyNode(from).addConstraintViolation();
        }
        return isValid;
    }
}
